// 博客多语言发布API
const express = require('express');
const router = express.Router();
const { MongoClient } = require('mongodb');

// 博客多语言发布配置
class BlogI18nAPI {
    constructor() {
        this.router = router;
        this.setupRoutes();
    }

    setupRoutes() {
        // 获取博客多语言配置
        router.get('/blog-i18n/config', this.getBlogI18nConfig.bind(this));
        
        // 更新博客多语言配置
        router.post('/blog-i18n/config', this.updateBlogI18nConfig.bind(this));
        
        // 获取博客多语言内容
        router.get('/blog-i18n/content/:blogId', this.getBlogI18nContent.bind(this));
        
        // 保存博客多语言内容
        router.post('/blog-i18n/content/:blogId', this.saveBlogI18nContent.bind(this));
        
        // 自动翻译博客内容
        router.post('/blog-i18n/translate/:blogId', this.translateBlogContent.bind(this));
        
        // 发布多语言博客
        router.post('/blog-i18n/publish/:blogId', this.publishBlogI18n.bind(this));
        
        // 获取博客多语言状态
        router.get('/blog-i18n/status/:blogId', this.getBlogI18nStatus.bind(this));
    }

    // 获取博客多语言配置
    async getBlogI18nConfig(req, res) {
        try {
            const client = await MongoClient.connect(process.env.MONGODB_URI);
            const db = client.db('blog_system');
            
            const config = await db.collection('blog_i18n_config').findOne({});
            
            if (!config) {
                // 返回默认配置
                const defaultConfig = {
                    enabled: true,
                    supportedLanguages: [
                        { code: 'zh-CN', name: '简体中文', enabled: true, autoTranslate: true },
                        { code: 'en-US', name: 'English', enabled: true, autoTranslate: true },
                        { code: 'ja-JP', name: '日本語', enabled: false, autoTranslate: false },
                        { code: 'ko-KR', name: '한국어', enabled: false, autoTranslate: false },
                        { code: 'fr-FR', name: 'Français', enabled: false, autoTranslate: false },
                        { code: 'de-DE', name: 'Deutsch', enabled: false, autoTranslate: false },
                        { code: 'es-ES', name: 'Español', enabled: false, autoTranslate: false },
                        { code: 'pt-BR', name: 'Português', enabled: false, autoTranslate: false },
                        { code: 'ru-RU', name: 'Русский', enabled: false, autoTranslate: false },
                        { code: 'it-IT', name: 'Italiano', enabled: false, autoTranslate: false },
                        { code: 'nl-NL', name: 'Nederlands', enabled: false, autoTranslate: false },
                        { code: 'pl-PL', name: 'Polski', enabled: false, autoTranslate: false },
                        { code: 'tr-TR', name: 'Türkçe', enabled: false, autoTranslate: false },
                        { code: 'vi-VN', name: 'Tiếng Việt', enabled: false, autoTranslate: false },
                        { code: 'th-TH', name: 'ไทย', enabled: false, autoTranslate: false },
                        { code: 'ar-SA', name: 'العربية', enabled: false, autoTranslate: false },
                        { code: 'hi-IN', name: 'हिन्दी', enabled: false, autoTranslate: false }
                    ],
                    defaultLanguage: 'zh-CN',
                    translationProvider: 'google', // google, baidu, deepl
                    autoPublish: false,
                    qualityCheck: true
                };
                
                await db.collection('blog_i18n_config').insertOne(defaultConfig);
                res.json(defaultConfig);
            } else {
                res.json(config);
            }
            
            client.close();
        } catch (error) {
            console.error('获取博客多语言配置失败:', error);
            res.status(500).json({ error: '获取配置失败' });
        }
    }

    // 更新博客多语言配置
    async updateBlogI18nConfig(req, res) {
        try {
            const config = req.body;
            const client = await MongoClient.connect(process.env.MONGODB_URI);
            const db = client.db('blog_system');
            
            await db.collection('blog_i18n_config').updateOne(
                {},
                { $set: config },
                { upsert: true }
            );
            
            client.close();
            res.json({ success: true, message: '配置更新成功' });
        } catch (error) {
            console.error('更新博客多语言配置失败:', error);
            res.status(500).json({ error: '更新配置失败' });
        }
    }

    // 获取博客多语言内容
    async getBlogI18nContent(req, res) {
        try {
            const { blogId } = req.params;
            const client = await MongoClient.connect(process.env.MONGODB_URI);
            const db = client.db('blog_system');
            
            const content = await db.collection('blog_i18n_content').findOne({ blogId });
            
            if (!content) {
                // 返回空的多语言内容结构
                const emptyContent = {
                    blogId,
                    originalLanguage: 'zh-CN',
                    translations: {},
                    status: 'draft',
                    createdAt: new Date(),
                    updatedAt: new Date()
                };
                res.json(emptyContent);
            } else {
                res.json(content);
            }
            
            client.close();
        } catch (error) {
            console.error('获取博客多语言内容失败:', error);
            res.status(500).json({ error: '获取内容失败' });
        }
    }

    // 保存博客多语言内容
    async saveBlogI18nContent(req, res) {
        try {
            const { blogId } = req.params;
            const content = req.body;
            const client = await MongoClient.connect(process.env.MONGODB_URI);
            const db = client.db('blog_system');
            
            await db.collection('blog_i18n_content').updateOne(
                { blogId },
                { 
                    $set: {
                        ...content,
                        updatedAt: new Date()
                    }
                },
                { upsert: true }
            );
            
            client.close();
            res.json({ success: true, message: '内容保存成功' });
        } catch (error) {
            console.error('保存博客多语言内容失败:', error);
            res.status(500).json({ error: '保存内容失败' });
        }
    }

    // 自动翻译博客内容
    async translateBlogContent(req, res) {
        try {
            const { blogId } = req.params;
            const { targetLanguages, content } = req.body;
            
            const client = await MongoClient.connect(process.env.MONGODB_URI);
            const db = client.db('blog_system');
            
            // 获取原始博客内容
            const originalBlog = await db.collection('blogs').findOne({ _id: blogId });
            
            if (!originalBlog) {
                return res.status(404).json({ error: '博客不存在' });
            }
            
            const translations = {};
            
            // 模拟翻译过程（实际项目中需要集成翻译API）
            for (const lang of targetLanguages) {
                translations[lang] = {
                    title: `[${lang}] ${originalBlog.title}`,
                    content: `这是 ${lang} 语言的博客内容翻译`,
                    summary: `[${lang}] ${originalBlog.summary || ''}`,
                    tags: originalBlog.tags || [],
                    status: 'translated',
                    translatedAt: new Date(),
                    quality: 'auto'
                };
            }
            
            // 保存翻译结果
            await db.collection('blog_i18n_content').updateOne(
                { blogId },
                {
                    $set: {
                        blogId,
                        originalLanguage: 'zh-CN',
                        translations,
                        status: 'translated',
                        updatedAt: new Date()
                    }
                },
                { upsert: true }
            );
            
            client.close();
            res.json({ 
                success: true, 
                message: '翻译完成', 
                translations 
            });
        } catch (error) {
            console.error('翻译博客内容失败:', error);
            res.status(500).json({ error: '翻译失败' });
        }
    }

    // 发布多语言博客
    async publishBlogI18n(req, res) {
        try {
            const { blogId } = req.params;
            const { languages } = req.body;
            
            const client = await MongoClient.connect(process.env.MONGODB_URI);
            const db = client.db('blog_system');
            
            // 获取多语言内容
            const i18nContent = await db.collection('blog_i18n_content').findOne({ blogId });
            
            if (!i18nContent) {
                return res.status(404).json({ error: '多语言内容不存在' });
            }
            
            // 发布到对应的语言版本
            for (const lang of languages) {
                const translation = i18nContent.translations[lang];
                if (translation && translation.status === 'translated') {
                    // 创建或更新多语言博客
                    await db.collection('blogs').updateOne(
                        { originalId: blogId, language: lang },
                        {
                            $set: {
                                title: translation.title,
                                content: translation.content,
                                summary: translation.summary,
                                tags: translation.tags,
                                language: lang,
                                originalId: blogId,
                                status: 'published',
                                publishedAt: new Date(),
                                updatedAt: new Date()
                            }
                        },
                        { upsert: true }
                    );
                    
                    // 更新翻译状态
                    i18nContent.translations[lang].status = 'published';
                    i18nContent.translations[lang].publishedAt = new Date();
                }
            }
            
            // 更新多语言内容状态
            i18nContent.status = 'published';
            i18nContent.updatedAt = new Date();
            
            await db.collection('blog_i18n_content').updateOne(
                { blogId },
                { $set: i18nContent }
            );
            
            client.close();
            res.json({ success: true, message: '多语言博客发布成功' });
        } catch (error) {
            console.error('发布多语言博客失败:', error);
            res.status(500).json({ error: '发布失败' });
        }
    }

    // 获取博客多语言状态
    async getBlogI18nStatus(req, res) {
        try {
            const { blogId } = req.params;
            const client = await MongoClient.connect(process.env.MONGODB_URI);
            const db = client.db('blog_system');
            
            const i18nContent = await db.collection('blog_i18n_content').findOne({ blogId });
            const config = await db.collection('blog_i18n_config').findOne({});
            
            const status = {
                blogId,
                hasI18nContent: !!i18nContent,
                supportedLanguages: config?.supportedLanguages || [],
                translations: i18nContent?.translations || {},
                overallStatus: i18nContent?.status || 'not_started',
                progress: this.calculateProgress(i18nContent, config)
            };
            
            client.close();
            res.json(status);
        } catch (error) {
            console.error('获取博客多语言状态失败:', error);
            res.status(500).json({ error: '获取状态失败' });
        }
    }

    // 计算翻译进度
    calculateProgress(i18nContent, config) {
        if (!i18nContent || !config) return 0;
        
        const enabledLanguages = config.supportedLanguages.filter(lang => lang.enabled);
        const translatedCount = Object.keys(i18nContent.translations || {}).length;
        
        return Math.round((translatedCount / enabledLanguages.length) * 100);
    }
}

module.exports = new BlogI18nAPI().router;